import Nabar from '@/conpoment/Nabar'
import { Button, Form, Input, Picker } from 'antd-mobile'
import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import http from '../../api/index'
import Djs from '../../hooks/UseDjs'
import axios from 'axios'
function Index() {
    const nav = useNavigate()
    const [relationshipVisible, setRelationshipVisible] = useState(false)
    const [relationshipValue, setRelationshipValue] = useState('')
    const [idTypeVisible, setIdTypeVisible] = useState(false)
    const [idTypeValue, setIdTypeValue] = useState('')
    const [addressVisible, setAddressVisible] = useState(false)
    const [addressValue, setAddressValue] = useState('')
    const [form] = Form.useForm()
    const [loading, setLoading] = useState(false)
    const [num, fn, disable] = Djs()
    const [from] = Form.useForm()
    const [codeValue, setCodeValue] = useState('')
    // 保存待回显的验证码，等待倒计时结束后再写入表单
    const pendingCodeRef = useRef<string | null>(null)
    const yzm = async () => {
        try {
            const yzms = await from.validateFields(['phone'])
            const { data: res } = await http.post('/api/login', { phone: yzms.phone })

            if (res.code === 20000) {
                // 先缓存验证码并清空输入框，待倒计时结束后再回显
                pendingCodeRef.current = String(res.data ?? '')
                setCodeValue('')  // 清空UI显示
                from.setFieldsValue({ code: '' })
                // 启动倒计时
                fn()
            } 
        } catch (error) {
            console.error('获取验证码失败:', error)
            alert('网络错误，请重试')
        }
    }
    // 倒计时结束（按钮从禁用变为可用）后，将验证码回显到表单
    useEffect(() => {
        if (!disable && pendingCodeRef.current) {
            const code = pendingCodeRef.current
            setCodeValue(code)  // 更新UI显示
            from.setFieldsValue({ code })  // 更新表单数据
            pendingCodeRef.current = null
        }
    }, [disable, from])
    const relationshipOptions = [
        { label: '请选择就诊人关系', value: '' },
        { label: '本人', value: '本人' },
        { label: '亲属', value: '亲属' },
        { label: '朋友', value: '朋友' },
    ]

    const idTypeOptions = [
        { label: '请选择证件类型', value: '' },
        { label: '居民身份证', value: '居民身份证' },
        { label: '港澳台通行证', value: '港澳台通行证' },
        { label: '外国护照', value: '外国护照' },
        { label: '军官证', value: '军官证' },
    ]

    const addressOptions = [
        { label: '请选择现住址', value: '' },
        { label: '北京市', value: '北京市' },
        { label: '上海市', value: '上海市' },
        { label: '广州市', value: '广州市' },
        { label: '深圳市', value: '深圳市' },
        { label: '杭州市', value: '杭州市' },
        { label: '南京市', value: '南京市' },
        { label: '武汉市', value: '武汉市' },
        { label: '成都市', value: '成都市' },
        { label: '西安市', value: '西安市' },
    ]


    // 提交表单
    const handleSubmit = async () => {
        try {
            setLoading(true)
            // 获取表单数据
            const formData = form.getFieldsValue()
            // 构建请求数据
            const requestData = {
                name: formData.name || '',
                standing: formData.standing || '',
                birthday: formData.birthday || '',
                sex: formData.sex || '',
                phone: formData.phone || '',
                relation: relationshipValue || '',
                age: formData.age || '',
                idType: idTypeValue || '',
                address: addressValue || '',
                addressDetail: formData.addressDetail || ''
            }
            // 调用API
            const response = await axios.put('/api/user/list', requestData)
            if (response.data.code === 20000) {
                // 保存用户信息到sessionStorage，供身份验证页面使用
                const userInfo = {
                    name: formData.name,
                    idType: idTypeValue,
                    idNumber: formData.standing
                }
                sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
                // 清空表单
                form.resetFields()
                setRelationshipValue('')
                setIdTypeValue('')
                setAddressValue('')
                
                // 跳转到身份验证页面
                    nav('/identity_verification')
               
            } 
        } catch (error) {
            console.error('提交失败:', error)
            alert('网络错误，请重试')
        } finally {
            setLoading(false)
        }
    }

    return (
        <div>
            <div>
                <Nabar title='添加患者' />
            </div>
            <b style={{ padding: '30px 10px' }}>请完善一下基本信息</b>
            <div>
                <Form form={form} layout='horizontal' mode='card'>
                    <Form.Item label='就诊人关系' name='relation'
                        extra={<p>ⅴ</p>}
                    >
                        <Input
                            placeholder={relationshipValue || '请选择就诊人关系'}
                            value={relationshipValue}
                            readOnly
                                onClick={() => {
                                    setRelationshipVisible(true);
                                }}
                            style={{
                                color: relationshipValue ? '#000' : '#999',
                                backgroundColor: relationshipValue ? '#fff' : '#f5f5f5'
                            }}
                        />
                    </Form.Item>
                    <Form.Item name='name' label='患者姓名'
                        rules={[{ required: true, message: '姓名不能为空!' }]}
                    >
                        <Input placeholder='请输入姓名' />
                    </Form.Item>
                    <Form.Item label='证件类型' name='idType' extra={<p>ⅴ</p>}>
                        <Input
                            placeholder={idTypeValue || '请选择证件类型'}
                            value={idTypeValue}
                            readOnly
                                onClick={() => {
                                    setIdTypeVisible(true);
                                }}
                            style={{
                                color: idTypeValue ? '#000' : '#999',
                                backgroundColor: idTypeValue ? '#fff' : '#f5f5f5'
                            }}
                        />
                    </Form.Item>
                    <Form.Item label='证件号'
                        name='standing'
                        rules={[{ required: true, message: '证件号不能为空!' }]}
                    >
                        <Input placeholder='请输入证件号' />
                    </Form.Item>
                    <Form.Item label='出生日期'
                        name='birthday'
                        rules={[{ required: true, message: '出生日期不能为空!' }]}
                    >
                        <Input placeholder='请输入出生日期' />
                    </Form.Item>
                    <Form.Item label='性别'
                        name='sex'
                        rules={[{ required: true, message: '性别不能为空!' }]}
                    >
                        <Input placeholder='请输入性别' />
                    </Form.Item>
                    <Form.Item label='年龄'
                        name='age'
                        rules={[{ required: true, message: '年龄不能为空!' }]}
                    >
                        <Input placeholder='请输入年龄' />
                    </Form.Item>
                    <Form.Item label='联系电话'
                        name='phone'
                        rules={[{ required: true, message: '联系电话不能为空!' }]}
                    >
                        <Input placeholder='请输入联系电话' />
                    </Form.Item>
                    <Form.Item label='短信验证码'
                        name='code'
                        rules={[
                            {
                                required: true, message: '验证码不能为空'
                            },
                        ]}
                    >
                        <div className="code-input-wrapper">
                            <Input
                                placeholder='输入验证码'
                                className="code-input"
                                value={codeValue}
                                onChange={(val) => {
                                    setCodeValue(val)
                                    from.setFieldsValue({ code: val })
                                }}
                            />
                            <Button style={{position: 'fixed', right: '0',top: '530px'}}
                                className="get-code-button"
                                onClick={yzm}
                                disabled={disable}
                            >
                                {disable ? `${num}秒后重新获取` : '获取验证码'}
                            </Button>
                        </div>
                    </Form.Item>














                    <Form.Item label='现住址' name='address' extra={<p>ⅴ</p>}
                        rules={[{ required: true, message: '现住址不能为空!' }]}
                    >
                        <Input
                            placeholder={addressValue || '请选择现住址'}
                            value={addressValue}
                            readOnly
                                onClick={() => {
                                    setAddressVisible(true);
                                }}
                            style={{
                                color: addressValue ? '#000' : '#999',
                                backgroundColor: addressValue ? '#fff' : '#f5f5f5'
                            }}
                        />
                    </Form.Item>

                    <Form.Item label='现住址详情' name='addressDetail'
                        rules={[{ required: true, message: '现住址详情不能为空!' }]}
                    >
                        <Input placeholder='请输入现住址详情' />
                    </Form.Item>
                </Form>
                <div style={{ padding: '0 10px', marginRight: '30px' }}>
                    <Button
                        block
                        color='primary'
                        style={{ margin: 20 }}
                        loading={loading}
                        onClick={handleSubmit}
                    >
                        绑定
                    </Button>
                </div>
            </div>

            {/* 就诊人关系选择器 */}
            <Picker
                columns={[relationshipOptions]}
                visible={relationshipVisible}
                onClose={() => setRelationshipVisible(false)}
                    onConfirm={(value) => {
                        // 确保 value 是数组且有值
                        if (value && value.length > 0) {
                            const selectedOption = relationshipOptions.find(option => option.value === value[0])
                            
                            if (selectedOption && selectedOption.value !== '') {
                                setRelationshipValue(selectedOption.label)
                            } else {
                                setRelationshipValue('')
                            }
                        } else {
                            setRelationshipValue('')
                        }
                        
                        setRelationshipVisible(false)
                    }}
                title="选择就诊人关系"
            />

            {/* 证件类型选择器 */}
            <Picker
                columns={[idTypeOptions]}
                visible={idTypeVisible}
                onClose={() => setIdTypeVisible(false)}
                    onConfirm={(value) => {
                        // 确保 value 是数组且有值
                        if (value && value.length > 0) {
                            const selectedOption = idTypeOptions.find(option => option.value === value[0])
                            
                            if (selectedOption && selectedOption.value !== '') {
                                setIdTypeValue(selectedOption.label)
                            } else {
                                setIdTypeValue('')
                            }
                        } else {
                            setIdTypeValue('')
                        }
                        
                        setIdTypeVisible(false)
                    }}
                title="选择证件类型"
            />

            {/* 现住址选择器 */}
            <Picker
                columns={[addressOptions]}
                visible={addressVisible}
                onClose={() => setAddressVisible(false)}
                    onConfirm={(value) => {
                        // 确保 value 是数组且有值
                        if (value && value.length > 0) {
                            const selectedOption = addressOptions.find(option => option.value === value[0])
                            
                            if (selectedOption && selectedOption.value !== '') {
                                setAddressValue(selectedOption.label)
                            } else {
                                setAddressValue('')
                            }
                        } else {
                            setAddressValue('')
                        }
                        
                        setAddressVisible(false)
                    }}
                title="选择现住址"
            />
        </div>
    )
}

export default Index
